# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals

# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter

# 取得 Cookies 清单
def get_cookies_dict():
    cookies_str = '7940D296A3BE781=19ED29CEE96C1DF9A458C4DF6B34C5613C6FB8896053E148EFD9CD53E6061194833FEAEE60CC50DEE3DC8F5701115798EE2C954EF75DD6D82991F182A3CA73B7A1013F9C6593E0C82097ACACBA083686514756F12424F122494A05550DB7E0F71E6E4CA09CBBDEE8ADCECE26715D5AAE8906A3E229CA216E19D43D060D0B0A9D68878ED17CEDE3878D8B63B1CA8B78185C80B4D9B973705F75F0764C376B42DA3DB6C8F6EA9C73FFEE9F7F23E99591E7A445278F75E20FF5807E4F3E3259C997A843FAFDBDE5E637000EABE15645F14195365F0AF844818AA63DD87FC05B1073F404BDB753DA5A0E62A6D1285491F374DC30E4C2CDAD62B5; Hm_lvt_fa0ea664baca46780244c3019bbfa951=1720171138; DM5_MACHINEKEY=db649b30-0ff4-4302-8d8a-9126d5492d38; SERVERID=node2; __utmc=1; __utmz=1.1720487570.2.2.utmcsr=baidu|utmccn=(organic)|utmcmd=organic; HMACCOUNT=28C402A5E9DB3517; Hm_lvt_6580fa76366dd7bfcf663327c0bcfbe2=1720487570; dm5cookieenabletest=1; firsturl=https%3A%2F%2Fwww.dm5.com%2Fm548925%2F; dm5imgpage=600805|8:1:71:0,549344|1:1:71:0,426475|1:1:71:0,426477|1:1:71:0,548925|1:1:71:0; dm5imgcooke=600805%7C8%2C549344%7C2%2C426475%7C2%2C426477%7C2%2C548925%7C2; __utma=1.1910407295.1705213079.1720487570.1720494989.3; appwelfare=3|1176378; firsturl=https%3A%2F%2Fwww.dm5.com%2Fm1176378%2F; readhistory_time=638561231293082846; ComicHistoryitem_zh=History=39028,638561134822010839,548925,1,0,0,0,1|33771,638561134572229085,426477,1,0,0,0,2|71347,638561231293082846,1176378,1,0,0,0,0&ViewType=0; Hm_lpvt_6580fa76366dd7bfcf663327c0bcfbe2=1720497529; Hm_lpvt_fa0ea664baca46780244c3019bbfa951=1720497529'
    cookies_dict = {}
    for item in cookies_str.split("; "):
        key, value = item.split("=", maxsplit=1)
        cookies_dict[key] = value
    return cookies_dict

# 获取 Cookies
COOKIES_DICT = get_cookies_dict()
# print(COOKIES_DICT)

class AcgnscrapySpiderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, or item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request or item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info("Spider opened: %s" % spider.name)


class AcgnscrapyDownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        request.cookies = COOKIES_DICT  # 请求时加入 Cookies 登入信息
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info("Spider opened: %s" % spider.name)
